/**
 * 医院管理面板组件
 * 提供医院、建筑、科室、设备的完整管理界面
 */

'use client'

import React, { useState, useEffect } from 'react'
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Badge } from "@/components/ui/badge"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { toast } from 'sonner'
import { Building2, Stethoscope, Wrench, Plus, Edit, Trash2, RefreshCw } from 'lucide-react'

// API导入
import { getHospitalBuildingsByHospital, deleteHospitalBuilding } from '@/lib/api/hospital-building'
import { getDepartmentsByHospital, deleteDepartment, getDepartmentTypes, getDepartmentStatusOptions } from '@/lib/api/department'
import { getMedicalEquipmentByHospital, deleteMedicalEquipment, getMedicalEquipmentTypes, getMedicalEquipmentStatusOptions } from '@/lib/api/medical-equipment'
import { hospitalDB } from '@/lib/indexedDB'

interface HospitalManagementPanelProps {
  className?: string
  onHospitalSelect?: (hospital: any) => void
  onBuildingSelect?: (building: any) => void
  onRefreshModel?: () => void
}

export const HospitalManagementPanel: React.FC<HospitalManagementPanelProps> = ({
  className = '',
  onHospitalSelect,
  onBuildingSelect,
  onRefreshModel
}) => {
  // 状态管理
  const [hospitals, setHospitals] = useState<any[]>([])
  const [buildings, setBuildings] = useState<any[]>([])
  const [departments, setDepartments] = useState<any[]>([])
  const [equipment, setEquipment] = useState<any[]>([])
  const [selectedHospital, setSelectedHospital] = useState<string>('')
  const [selectedBuilding, setSelectedBuilding] = useState<string>('')
  const [isLoading, setIsLoading] = useState(false)

  // 获取数据的辅助函数
  const departmentTypes = getDepartmentTypes()
  const departmentStatusOptions = getDepartmentStatusOptions()
  const equipmentTypes = getMedicalEquipmentTypes()
  const equipmentStatusOptions = getMedicalEquipmentStatusOptions()

  // 加载医院列表
  const loadHospitals = async () => {
    setIsLoading(true)
    try {
      console.log('开始加载医院列表...')
      
      // 优先尝试从真实API获取医院数据
      let result = []
      try {
        const { hospitalAPI } = await import('@/lib/api/hospital')
        const response = await hospitalAPI.getSites({
          status: 'active',
          limit: 100
        })
        
        if (response?.success && response?.data?.sites) {
          result = response.data.sites.map((site: any) => ({
            id: site.siteId,
            name: site.name,
            address: site.address,
            center: [site.coordinates.longitude, site.coordinates.latitude],
            zoom: site.zoom || 16,
            city: site.city,
            province: site.province
          }))
          console.log('成功从API获取医院数据:', result.length)
        }
      } catch (apiError) {
        console.warn('API获取失败，尝试从IndexedDB获取:', apiError)
      }
      
      // 如果API获取失败，回退到IndexedDB
      if (result.length === 0) {
        result = await hospitalDB.getHospitals()
        console.log('从IndexedDB获取医院数据:', result?.length || 0)
      }
      
      console.log('加载到的医院数据:', result)
      
      if (result && result.length > 0) {
        setHospitals(result)
        if (!selectedHospital) {
          setSelectedHospital(result[0].id)
          console.log('自动选择第一个医院:', result[0].name)
        }
      } else {
        console.log('没有找到医院数据')
        toast.error('没有找到医院数据，请检查数据初始化')
      }
    } catch (error) {
      console.error('加载医院列表失败:', error)
      toast.error('加载医院列表失败: ' + (error instanceof Error ? error.message : '未知错误'))
    } finally {
      setIsLoading(false)
    }
  }

  // 加载选中医院的建筑
  const loadHospitalBuildings = async (hospitalId: string) => {
    if (!hospitalId) return

    try {
      const result = await getHospitalBuildingsByHospital(hospitalId)
      if (result.success && result.data) {
        setBuildings(result.data)
      }
    } catch (error) {
      console.error('加载医院建筑失败:', error)
      toast.error('加载医院建筑失败')
    }
  }

  // 加载选中医院的科室和设备
  const loadHospitalData = async (hospitalId: string) => {
    if (!hospitalId) return

    try {
      const [departmentsResult, equipmentResult] = await Promise.all([
        getDepartmentsByHospital(hospitalId),
        getMedicalEquipmentByHospital(hospitalId)
      ])

      if (departmentsResult.success && departmentsResult.data) {
        setDepartments(departmentsResult.data)
      }

      if (equipmentResult.success && equipmentResult.data) {
        setEquipment(equipmentResult.data)
      }
    } catch (error) {
      console.error('加载医院数据失败:', error)
      toast.error('加载医院数据失败')
    }
  }

  // 初始化和响应选择变化
  useEffect(() => {
    // 延迟一点时间等待IndexedDB初始化完成
    const timer = setTimeout(() => {
      loadHospitals()
    }, 1000)
    
    return () => clearTimeout(timer)
  }, [])

  useEffect(() => {
    if (selectedHospital) {
      loadHospitalBuildings(selectedHospital)
      loadHospitalData(selectedHospital)
      const hospital = hospitals.find(h => h.id === selectedHospital)
      onHospitalSelect?.(hospital)
    }
  }, [selectedHospital, hospitals])

  useEffect(() => {
    if (selectedBuilding) {
      const building = buildings.find(b => b.id === selectedBuilding)
      onBuildingSelect?.(building)
    }
  }, [selectedBuilding, buildings])

  // 删除操作
  const handleDeleteBuilding = async (id: string) => {
    if (!confirm('确定要删除这个建筑吗？这将同时删除相关的科室和设备数据。')) {
      return
    }

    try {
      const result = await deleteHospitalBuilding(id)
      if (result.success) {
        toast.success(result.msg)
        loadHospitalBuildings(selectedHospital)
        if (selectedBuilding === id) {
          setSelectedBuilding('')
        }
      } else {
        toast.error(result.msg)
      }
    } catch (error) {
      console.error('删除建筑失败:', error)
      toast.error('删除建筑失败')
    }
  }

  const handleDeleteDepartment = async (id: string) => {
    if (!confirm('确定要删除这个科室吗？')) {
      return
    }

    try {
      const result = await deleteDepartment(id)
      if (result.success) {
        toast.success(result.msg)
        loadHospitalData(selectedHospital)
      } else {
        toast.error(result.msg)
      }
    } catch (error) {
      console.error('删除科室失败:', error)
      toast.error('删除科室失败')
    }
  }

  const handleDeleteEquipment = async (id: string) => {
    if (!confirm('确定要删除这个设备吗？')) {
      return
    }

    try {
      const result = await deleteMedicalEquipment(id)
      if (result.success) {
        toast.success(result.msg)
        loadHospitalData(selectedHospital)
      } else {
        toast.error(result.msg)
      }
    } catch (error) {
      console.error('删除设备失败:', error)
      toast.error('删除设备失败')
    }
  }

  // 获取科室类型标签
  const getDepartmentTypeLabel = (value: string) => {
    const type = departmentTypes.find(t => t.type === value)
    return type ? `${type.icon} ${type.label}` : value
  }

  // 获取设备类型标签
  const getEquipmentTypeLabel = (value: string) => {
    const type = equipmentTypes.find(t => t.type === value)
    return type ? `${type.icon} ${type.label}` : value
  }

  // 获取状态颜色
  const getStatusColor = (status: string, type: 'department' | 'equipment') => {
    const options = type === 'department' ? departmentStatusOptions : equipmentStatusOptions
    const option = options.find(o => o.value === status)
    return option?.color || '#6b7280'
  }

  return (
    <div className={`space-y-4 ${className}`}>
      {/* 头部操作栏 */}
      <Card>
        <CardHeader className="pb-3">
          <div className="flex items-center justify-between">
            <CardTitle className="text-lg">医院数据管理</CardTitle>
            <div className="flex items-center gap-2">
              {selectedBuilding && (
                <Button
                  size="sm"
                  variant="outline"
                  onClick={() => onRefreshModel?.(selectedBuilding)}
                  className="gap-1"
                >
                  <RefreshCw className="w-4 h-4" />
                  刷新模型
                </Button>
              )}
            </div>
          </div>
        </CardHeader>
        <CardContent className="space-y-3">
          <div className="flex items-center gap-3">
            <label className="text-sm font-medium whitespace-nowrap">
              当前医院：
            </label>
            <Select value={selectedHospital} onValueChange={setSelectedHospital}>
              <SelectTrigger className="w-full">
                <SelectValue placeholder="选择医院" />
              </SelectTrigger>
              <SelectContent>
                {hospitals.map((hospital) => (
                  <SelectItem key={hospital.id} value={hospital.id}>
                    {hospital.name}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>

          {buildings.length > 0 && (
            <div className="flex items-center gap-3">
              <label className="text-sm font-medium whitespace-nowrap">
                选择建筑：
              </label>
              <Select value={selectedBuilding} onValueChange={setSelectedBuilding}>
                <SelectTrigger className="w-full">
                  <SelectValue placeholder="选择建筑" />
                </SelectTrigger>
                <SelectContent>
                  {buildings.map((building) => (
                    <SelectItem key={building.id} value={building.id}>
                      {building.name}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          )}
        </CardContent>
      </Card>

      {/* 主要内容区域 */}
      {selectedHospital ? (
        <Tabs defaultValue="buildings" className="space-y-4">
          <TabsList className="grid w-full grid-cols-3">
            <TabsTrigger value="buildings" className="gap-2">
              <Building2 className="w-4 h-4" />
              建筑管理
            </TabsTrigger>
            <TabsTrigger value="departments" className="gap-2">
              <Stethoscope className="w-4 h-4" />
              科室管理
            </TabsTrigger>
            <TabsTrigger value="equipment" className="gap-2">
              <Wrench className="w-4 h-4" />
              设备管理
            </TabsTrigger>
          </TabsList>

          {/* 建筑管理 */}
          <TabsContent value="buildings">
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center justify-between">
                  医院建筑列表
                  <Badge variant="secondary">{buildings.length} 个建筑</Badge>
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="space-y-3">
                  {buildings.map((building) => (
                    <div
                      key={building.id}
                      className={`flex items-center justify-between p-3 border rounded-lg cursor-pointer transition-colors ${
                        selectedBuilding === building.id ? 'border-blue-500 bg-blue-50' : 'hover:bg-gray-50'
                      }`}
                      onClick={() => setSelectedBuilding(building.id)}
                    >
                      <div className="flex-1">
                        <div className="font-medium">{building.name}</div>
                        <div className="text-sm text-gray-500 mt-1">
                          {building.description}
                        </div>
                        <div className="text-xs text-gray-400 mt-1">
                          中心坐标: {building.center[0].toFixed(4)}, {building.center[1].toFixed(4)}
                        </div>
                        {building.floors.length > 0 && (
                          <div className="flex gap-1 mt-2">
                            {building.floors.map((floor: string) => (
                              <Badge key={floor} variant="outline" className="text-xs">
                                {floor}
                              </Badge>
                            ))}
                          </div>
                        )}
                      </div>
                      <div className="flex items-center gap-2 ml-4">
                        <Button
                          size="sm"
                          variant="outline"
                          onClick={(e) => {
                            e.stopPropagation()
                            // 编辑建筑逻辑
                          }}
                        >
                          <Edit className="w-4 h-4" />
                        </Button>
                        <Button
                          size="sm"
                          variant="outline"
                          onClick={(e) => {
                            e.stopPropagation()
                            handleDeleteBuilding(building.id)
                          }}
                          className="text-red-600 hover:text-red-700"
                        >
                          <Trash2 className="w-4 h-4" />
                        </Button>
                      </div>
                    </div>
                  ))}
                  {buildings.length === 0 && (
                    <div className="text-center py-8 text-gray-500">
                      暂无建筑数据，请先添加医院建筑
                    </div>
                  )}
                </div>
              </CardContent>
            </Card>
          </TabsContent>

          {/* 科室管理 */}
          <TabsContent value="departments">
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center justify-between">
                  科室列表
                  <Badge variant="secondary">{departments.length} 个科室</Badge>
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="space-y-3">
                  {departments.map((department) => (
                    <div
                      key={department.id}
                      className="flex items-center justify-between p-3 border rounded-lg"
                    >
                      <div className="flex-1">
                        <div className="flex items-center gap-2">
                          <span className="font-medium">{department.name}</span>
                          <Badge variant="outline">
                            {getDepartmentTypeLabel(department.type)}
                          </Badge>
                          <div
                            className="w-2 h-2 rounded-full"
                            style={{ backgroundColor: getStatusColor(department.status, 'department') }}
                            title={departmentStatusOptions.find(s => s.value === department.status)?.label}
                          />
                        </div>
                        {department.description && (
                          <div className="text-sm text-gray-500 mt-1">
                            {department.description}
                          </div>
                        )}
                        <div className="text-xs text-gray-400 mt-1">
                          位置: {department.position[0].toFixed(4)}, {department.position[1].toFixed(4)}
                        </div>
                        {department.contact?.director && (
                          <div className="text-xs text-gray-400">
                            负责人: {department.contact.director}
                          </div>
                        )}
                        {department.capacity && (
                          <div className="text-xs text-gray-400">
                            容量: {department.capacity}
                          </div>
                        )}
                      </div>
                      <div className="flex items-center gap-2 ml-4">
                        <Button
                          size="sm"
                          variant="outline"
                          onClick={() => {
                            // 编辑科室逻辑
                          }}
                        >
                          <Edit className="w-4 h-4" />
                        </Button>
                        <Button
                          size="sm"
                          variant="outline"
                          onClick={() => handleDeleteDepartment(department.id)}
                          className="text-red-600 hover:text-red-700"
                        >
                          <Trash2 className="w-4 h-4" />
                        </Button>
                      </div>
                    </div>
                  ))}
                  {departments.length === 0 && (
                    <div className="text-center py-8 text-gray-500">
                      暂无科室数据，点击3D模型绑定科室信息
                    </div>
                  )}
                </div>
              </CardContent>
            </Card>
          </TabsContent>

          {/* 设备管理 */}
          <TabsContent value="equipment">
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center justify-between">
                  医疗设备列表
                  <Badge variant="secondary">{equipment.length} 个设备</Badge>
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="space-y-3">
                  {equipment.map((item) => (
                    <div
                      key={item.id}
                      className="flex items-center justify-between p-3 border rounded-lg"
                    >
                      <div className="flex-1">
                        <div className="flex items-center gap-2">
                          <span className="font-medium">{item.name}</span>
                          <Badge variant="outline">
                            {getEquipmentTypeLabel(item.type)}
                          </Badge>
                          <div
                            className="w-2 h-2 rounded-full"
                            style={{ backgroundColor: getStatusColor(item.status, 'equipment') }}
                            title={equipmentStatusOptions.find(s => s.value === item.status)?.label}
                          />
                        </div>
                        {item.description && (
                          <div className="text-sm text-gray-500 mt-1">
                            {item.description}
                          </div>
                        )}
                        <div className="text-xs text-gray-400 mt-1">
                          位置: {item.position[0].toFixed(4)}, {item.position[1].toFixed(4)}
                        </div>
                        {item.manufacturer && (
                          <div className="text-xs text-gray-400">
                            制造商: {item.manufacturer}
                          </div>
                        )}
                        {item.specifications && (
                          <div className="text-xs text-gray-400">
                            规格: {item.specifications}
                          </div>
                        )}
                      </div>
                      <div className="flex items-center gap-2 ml-4">
                        <Button
                          size="sm"
                          variant="outline"
                          onClick={() => {
                            // 编辑设备逻辑
                          }}
                        >
                          <Edit className="w-4 h-4" />
                        </Button>
                        <Button
                          size="sm"
                          variant="outline"
                          onClick={() => handleDeleteEquipment(item.id)}
                          className="text-red-600 hover:text-red-700"
                        >
                          <Trash2 className="w-4 h-4" />
                        </Button>
                      </div>
                    </div>
                  ))}
                  {equipment.length === 0 && (
                    <div className="text-center py-8 text-gray-500">
                      暂无设备数据，点击地图绑定医疗设备
                    </div>
                  )}
                </div>
              </CardContent>
            </Card>
          </TabsContent>
        </Tabs>
      ) : (
        <Card>
          <CardContent className="text-center py-8 text-gray-500">
            请先选择一个医院
          </CardContent>
        </Card>
      )}
    </div>
  )
}